<script setup lang='ts'>
import { ref } from 'vue'
import Detail from './workDetail.vue'
import StatusDialog from './statusDialog.vue'
import type { StoryItem } from '../../../apis/story/type'
import { disabledDate, shortcuts } from '../../../utils/time'
import { reqDeleteProjectStoryBystory, reqUpdateProjectStoryBystory } from '../../../apis/story'
import { ElMessage } from 'element-plus'
import { reqGetAllMemberProjectById } from '../../../apis/project'
import { useRoute } from 'vue-router'
import { onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { watch } from 'vue'
import { formatDate, formatDateISOS } from '../../../utils/time'
import type { ProjectMember } from '../../../apis/project/type'

const props = defineProps<{
  workData: StoryItem[],
  height?: string
}>()
let originalData = JSON.parse(JSON.stringify(props.workData))
const $route = useRoute()
const dialogVisible = ref<boolean>(false)
const detailVisible = ref<boolean>(false)
const currentRow = ref<StoryItem>({} as StoryItem)
const currentIndex = ref<number>(0)
const memberList = ref<ProjectMember[]>([])
let projectId = ref<number | null | undefined>($route.params.id ? Number($route.params.id) : null)
const loading = ref<boolean>(false)
const priorityOptions = [
  {
    value: 'high',
    label: '高',
  },
  {
    value: 'medium',
    label: '中',
  },
  {
    value: 'low',
    label: '低',
  }
]


const handlerPrevRow = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
    currentRow.value = props.workData[currentIndex.value];
    projectId.value = props.workData[currentIndex.value].projectId
  }
}

const handlerNextRow = () => {
  if (currentIndex.value < props.workData.length - 1) {
    currentIndex.value++;
    currentRow.value = props.workData[currentIndex.value];
  }
}

const getmemberList = async () => {
  const res = await reqGetAllMemberProjectById(projectId.value as number)
  if (res.code === 200) {
    memberList.value = res.data
  }
}

// 状态管理
const editable = ref<{ [key: string]: boolean }>({})

const startEdit = (rowIndex: number, column: string, pId?: number) => {
  editable.value[`${rowIndex}-${column}`] = true
  if (column === 'assignees') {
    projectId.value = pId
  }
}

const emit = defineEmits(['refresh'])

const saveEdit = async (rowIndex: number, column: string, row: StoryItem) => {
  loading.value = true
  try {
    let assigneeIds = row.assignees ? row.assignees.map((item: any) => item.id) : []
    endEdit(rowIndex, column)
    const res = await reqUpdateProjectStoryBystory(row.projectId, row.id, {
      title: row.title,
      description: row.description,
      priority: row.priority,
      versionId: row.versionId,
      parentId: row.parentId,
      endsAt: row.endsAt ? formatDateISOS(row.endsAt) : null,
      assigneeIds: assigneeIds
    })
    if (res.code === 200) {
      ElMessage.success('保存成功')
      emit('refresh')
    }
  } catch (error) {
    Object.assign(row, props.workData[rowIndex])
  } finally {
    loading.value = false
  }
}

const handlerDeletestory = async (row: StoryItem) => {
  ElMessageBox.confirm(`确认删除需求 ${row.title} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    const res = await reqDeleteProjectStoryBystory(row.projectId, row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      emit('refresh')
    }
  }).finally(() => {
    loading.value = false
  })
}

const endEdit = (rowIndex: number, column: string) => {
  editable.value[`${rowIndex}-${column}`] = false
}

const OpenDrawer = (row: StoryItem, index: number) => {
  currentRow.value = row
  currentIndex.value = index
  projectId.value = row.projectId
  detailVisible.value = true
}

const getPriorityText = (priority: string) => {
  const priorityTextMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityTextMap[priority as keyof typeof priorityTextMap] || priority
}

const getStatusText = (status: string) => {
  const statusTextMap: Record<string, string> = {
    'new': '新建',
    'in-progress': '实现中',
    'completed': '已实现',
    'rejected': '已拒绝'
  }
  return statusTextMap[status as keyof typeof statusTextMap] || status
}

const filterPriority = (value: string, row: StoryItem) => {
  return row.priority === value
}

const filterStatus = (value: string, row: StoryItem) => {
  return row.status === value
}

const handleStatus = (row: StoryItem, index: number) => {
  currentRow.value = row
  currentIndex.value = index
  projectId.value = row.projectId
  dialogVisible.value = true
}

onMounted(() => {
  getmemberList()
})

watch(projectId, newVal => {
  if (newVal) {
    getmemberList()
  }
})

watch(() => props.workData, (newVal) => {
  originalData = JSON.parse(JSON.stringify(newVal))
}, { deep: true })

</script>

<template>
  <el-table :data="originalData" row-key="id" :height="height" v-loading="loading">
    <!-- 标题列 -->
    <el-table-column fixed prop="title" label="标题" width="300" show-overflow-tooltip>
      <template #default="{ row, $index }">
        <el-input v-if="editable[`${$index}-title`]" v-model="row.title"
          @keyup.enter.native="saveEdit($index, 'title', row)" @blur="saveEdit($index, 'title', row)" autofocus
          style="max-width: 220px;" />
        <template v-else>
          <span class="editable-text" @click="OpenDrawer(row, $index)">{{ row.title }}</span>
          <el-button size="small" type="info" circle @click="startEdit($index, 'title')" style="float: right;"><el-icon>
              <Edit />
            </el-icon></el-button>
        </template>
      </template>
    </el-table-column>

    <!-- 状态列 -->
    <el-table-column prop="status" label="状态" :filters="[
      { text: '新建', value: 'new' },
      { text: '实现中', value: 'in-progress' },
      { text: '已实现', value: 'completed' },
      { text: '已拒绝', value: 'rejected' }
    ]" :filter-method="filterStatus">
      <template #default="{ row, $index }">
        <el-button :type="row.status === 'new' ? 'primary' :
          row.status === 'in-progress' ? 'warning' :
            row.status === 'completed' ? 'success' :
              'danger'" round plain @click="handleStatus(row, $index)">{{ getStatusText(row.status) }}</el-button>
      </template>
    </el-table-column>

    <!-- 优先级列 -->
    <el-table-column prop="priority" label="优先级" :filters="[
      { text: '高', value: 'high' },
      { text: '中', value: 'medium' },
      { text: '低', value: 'low' }
    ]" :filter-method="filterPriority">
      <template #default="{ row, $index }">
        <el-select v-if="editable[`${$index}-priority`]" v-model="row.priority"
          @keyup.enter.native="saveEdit($index, 'priority', row)" @blur="saveEdit($index, 'priority', row)"
          @change="saveEdit($index, 'priority', row)" autofocus>
          <template #label>
            <el-tag size="middle"
              :type="row.priority === 'high' ? 'danger' : row.priority === 'medium' ? 'warning' : 'primary'">
              -{{ getPriorityText(row.priority) }}-
            </el-tag>
          </template>
          <el-option v-for="item in priorityOptions" :key="item.value" :value="item.value" :label="item.label">
            <el-tag size="middle"
              :type="item.value === 'high' ? 'danger' : item.value === 'medium' ? 'warning' : 'primary'">-{{
                item.label }}-</el-tag>
          </el-option>
        </el-select>
        <el-tag v-else size="middle" @click="startEdit($index, 'priority')" class="editable-text priority-tag"
          :type="row.priority === 'high' ? 'danger' : row.priority === 'medium' ? 'warning' : 'primary'">-{{
            getPriorityText(row.priority) }}-</el-tag>
      </template>
    </el-table-column>

    <!-- 预计结束列 -->
    <el-table-column prop="endsAt" label="预计结束" sortable>
      <template #default="{ row, $index }">
        <el-date-picker v-if="editable[`${$index}-endsAt`]" v-model="row.endsAt" :disabled-date="disabledDate"
          :shortcuts="shortcuts" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" style="width: 150px;"
          placeholder="选择日期" clearable @change="saveEdit($index, 'endsAt', row)"
          @blur="saveEdit($index, 'endsAt', row)" />
        <span v-else @click="startEdit($index, 'endsAt')" class="editable-text">
          {{ row.endsAt ? formatDate(row.endsAt) : '-' }}
        </span>
      </template>
    </el-table-column>

    <!-- 处理人列 -->
    <el-table-column prop="assignees" label="处理人" width="180" show-overflow-tooltip>
      <template #default="{ row, $index }">
        <div class="m-4" width="140" v-if="editable[`${$index}-assignees`]">
          <el-select v-model="row.assignees" multiple collapse-tags collapse-tags-tooltip placeholder="请选择处理人"
            @blur="saveEdit($index, 'assignees', row)" value-key="id" lazy>
            <el-option v-for="item in memberList" :key="item.id" :label="item.username" :value="item" />
          </el-select>
        </div>
        <span v-else @click="startEdit($index, 'assignees', row.projectId)" class="editable-text">{{
          row.assignees && row.assignees.length > 0 ? row.assignees.map((item: any) => item.username).join(';') : '-'
        }}</span>
      </template>
    </el-table-column>

    <!-- 创建时间列 -->
    <el-table-column prop="createdAt" label="创建时间" sortable>
      <template #default="{ row }">
        <span>{{ formatDate(row.createdAt) }}</span>
        <el-button type="info" size="small" circle @click="handlerDeletestory(row)"
          style="opacity: 0; transition: opacity 0.3s; float:right" class="delete-btn">
          <el-icon>
            <Close />
          </el-icon>
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <StatusDialog v-model:dialogVisible="dialogVisible" :rowData="currentRow" :memberList="memberList"
    @refresh="emit('refresh')"></StatusDialog>

  <Detail v-model:detailVisible="detailVisible" :rowData="currentRow" @prev-row="handlerPrevRow"
    @next-row="handlerNextRow" :memberList="memberList" @refresh="emit('refresh')"></Detail>
</template>


<style scoped lang='scss'>
.editable-text {
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;



  .el-button {
    padding: 5px 10px;
    min-height: auto;
  }
}

:deep(.el-date-editor) {
  width: 120px;
}

:deep(.el-table__row:hover) {
  .delete-btn {
    opacity: 1 !important;
  }
}

.priority-tag {
  transform: none !important;
  transition: none !important;

  &:hover {
    transform: none !important;
  }
}
</style>